<?php
namespace App\Tools;
use OSS\Core\OssException;
use OSS\OssClient;

function classLoader($class)
{
    $path = str_replace('\\', DIRECTORY_SEPARATOR, $class);
    $file = __DIR__ . DIRECTORY_SEPARATOR.$path . '.php';
    if (file_exists($file)) {
        require_once $file;
    }
}
spl_autoload_register('app\Tools\classLoader');

class AliOss{
    public $oss = null;
    public $config = null;

    public function __construct()
    {
        $this->config = $this->getOssConfig();
        $this->oss = new OssClient($this->config['OSS_ACCESS_ID'], $this->config['OSS_ACCESS_KEY'], $this->config['ENDPOINT']);
    }

    public function toOSS($object,$filePath){
        try{
            $this->oss->uploadFile($this->config['OSS_BUCKET'], $object, $filePath);
            return true;
        }catch (OssException $e){
            printf(__FUNCTION__ . ": FAILED\n");
            printf($e->getMessage() . "\n");
            return false;
        }
    }

    public function getOssConfig(){
        static $config = null;

        if ($config == null){
            $config = require 'oss_config.php';
        }
        return $config;
    }


    //图片添加图片水印
    /*  $img：oss图片链接（不带域名）
     *  $watermark_img ：oss下水印图片链接（不带域名）
     *  $p : 水印图片缩放比例
     *  $t : 水印图片透明度  [0-100] 100表示不透明
     *  $position: 水印图片位置，取值为[nw,north,ne,west,center,east,sw,south,se]
     *  $voffset : 上下偏移量 整数，正值往上偏移，负值往下偏移
     * */
    public function watermark($img,$watermark_img,$p=50,$t=90,$position='center',$voffset=0){


        $watermark_img = $watermark_img.'?x-oss-process=image/resize,P_'.$p;

        $str = base64_encode($watermark_img);
        $str = str_replace(array('+','/'),array('-','_'),$str);

        $set = '?x-oss-process=image/resize,w_300/watermark,image_'.$str.',t_'.$t.',g_'.$position.',voffset_'.$voffset;

        $img_url = $this->config['OSS_VIEW_HOST'].$img.$set;

        return $img_url;

    }
}

?>